const mysqlDB = require('./config/mysqlDB.config')
const Aritle = mysqlDB.import('./modules/aritle')
const Tag = mysqlDB.import('./modules/tag')
const AritleToTag = mysqlDB.import('./modules/aritleToTag')

const aritleList = [
  {
    name: '史记',
    tag: '文学'
  },
  {
    name: '春秋',
    tag: '兵书,历史'
  },
  {
    name: '西游记',
    tag: '小说,神话传说,文学'
  },
  {
    name: '红楼梦',
    tag: '小说,现实故事,文学'
  },
  {
    name: '本草纲目',
    tag: '医术'
  },
  {
    name: '左传',
    tag: '文学,历史,兵书'
  }
]

// 1. 创建 aritle
// 2. 创建 tag
// 3. 添加关联关系 Belongs-To-Many 会自动为 aritle 和 tag 添加对应的方法
// https://segmentfault.com/a/1190000017320533
const createTag = async tag => {
  return await Tag.findOrCreate({
    where: { name: tag },
    defaults: { name: tag }
  })
}
const createAritle = async aritle => {
  return await Aritle.findOrCreate({
    where: { name: aritle },
    defaults: { name: aritle }
  })
}

const main = async () => {
  let len = aritleList.length
  for (let i = 0; i < len; i++) {
    let name = aritleList[i].name
    let tags = aritleList[i].tag.split(',')
    let aritle = await createAritle(name)
    const aritleInstence = aritle[0]
    let aritle_id = aritle && aritle.length ? aritle[0].id : false
    // console.dir(aritleInstence.setTags)
    // console.log(aritleInstence.getTags)
    // console.log(aritleInstence.addTags)
    // console.dir(aritleInstence.addTag)
    if (aritle_id) {
      let currentTags = []
      for (let y = 0; y < tags.length; y++) {
        let tagInstence = await createTag(tags[y])
        currentTags.push(tagInstence[0])
      }
      let result = await aritleInstence.addTags(currentTags)
      if (result) {
        console.log(JSON.parse(JSON.stringify(result)))
      }
    }

    // for () {
    //   let tagInstence = await createTag(tags[sub])
    //   let tag_id = tagInstence && tagInstence.length ? tagInstence[0].id : false
    //   if (tag_id && aritle_id) {
    //     try {
    //       let result = await aritleInstence.addTags(tagInstence[0])
    //       console.log(result)
    //     } catch (error) {
    //       console.log(error)
    //     }
    //   }
    // }
  }
}

const changeTag = async () => {
  const aritleInstence = await Aritle.findOne({
    where: {
      name: '史记'
    }
  })
  const tagInstence = await createTag('逗我玩')
  const list = await aritleInstence.removeTags([tagInstence[0]])
  // const list = await aritleInstence.addTags([tagInstence[0]])
  console.log(JSON.parse(JSON.stringify(list)))
}

async function index() {
  await Aritle.sync({ alter: true })
  await Tag.sync({ alter: true })
  await AritleToTag.sync({ alter: true })
  // main()
  changeTag()
}

index()

// 多对多删除
// 修改一条数据的对多对
// 使用 setTag([tag1,tag2])
// https://www.codercto.com/a/32151.html

// sequelize中文文档 https://itbilu.com/nodejs/npm/41qaV3czb.html
